<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\controller;
use App\AccountLog;
use app\common\model\AppAccountLog;
use app\common\model\ApplicationOrder;
use app\common\model\ThirdApplicationResultLog;

use think\Db;

use function Qiniu\json_decode;

/**
 * 配置控制器
 */
class ApplicationThird extends AdminBase
{

    private function api_key(){
        return "b421b9a21075a359c09a36db79325d5b";
    }

    private function api_secret(){
        return "d3243685d9922998ddd4232f38b53555";
    }

    public function api_url(){
        return "http://apitest.99263.com";
    }

    public function ApplicationThirdList()
    {

        $train_orders = Db::name("train_application_order")->alias('a')->field("a.*,b.username")->join("__MEMBER__ b","a.user_id=b.id")->where('1=1')->select();
        $list = array();
        foreach ($train_orders as $k=>$v){
            $train_orders[$k]['fail_remark'] = Db::name("third_application_result_log")->field("result_msg,create_time")->where(["type"=>2,"app_id"=>$v["id"]])->order("create_time desc")->limit(3)->select();
            $list[]=$train_orders[$k];
        }

        $flight_orders = Db::name("flight_application_order")->alias('a')->field("a.*,b.username")->join("__MEMBER__ b","a.user_id=b.id")->where('1=1')->select();
        foreach ($flight_orders as $k=>$v){
            $flight_orders[$k]['fail_remark'] = Db::name("third_application_result_log")->field("result_msg,create_time")->where(["type"=>3,"app_id"=>$v["id"]])->order("create_time desc")->limit(3)->select();
            $list[]=$flight_orders[$k];
        }

        $hotel_orders = Db::name("hotel_application_order")->alias('a')->field("a.*,b.username")->join("__MEMBER__ b","a.user_id=b.id")->where('1=1')->select();
        foreach ($hotel_orders as $k=>$v){
            $hotel_orders[$k]['fail_remark'] = Db::name("third_application_result_log")->field("result_msg,create_time")->where(["type"=>1,"app_id"=>$v["id"]])->order("create_time desc")->limit(3)->select();
            $list[]=$hotel_orders[$k];
        }

        $didi_orders = Db::name("didi_application_order")->alias('a')->field("a.*,b.username")->join("__MEMBER__ b","a.user_id=b.id")->where('1=1')->select();
        foreach ($didi_orders as $k=>$v){
            $didi_orders[$k]['fail_remark'] = Db::name("third_application_result_log")->field("result_msg,create_time")->where(["type"=>6,"app_id"=>$v["id"]])->order("create_time desc")->limit(3)->select();
            $list[]=$didi_orders[$k];
        }

        $mobile_orders = Db::name("mobile_application_order")->alias('a')->field("a.*,b.username")->join("__MEMBER__ b","a.user_id=b.id")->where('1=1')->select();
        foreach ($mobile_orders as $k=>$v){
            $mobile_orders[$k]['fail_remark'] = Db::name("third_application_result_log")->field("result_msg,create_time")->where(["type"=>4,"app_id"=>$v["id"]])->order("create_time desc")->limit(3)->select();
            $list[]=$mobile_orders[$k];
        }

        $oil_orders = Db::name("oil_application_order")->alias('a')->field("a.*,b.username")->join("__MEMBER__ b","a.user_id=b.id")->where('1=1')->select();
        foreach ($oil_orders as $k=>$v){
            $oil_orders[$k]['fail_remark'] = Db::name("third_application_result_log")->field("result_msg,create_time")->where(["type"=>5,"app_id"=>$v["id"]])->order("create_time desc")->limit(3)->select();
            $list[]=$oil_orders[$k];
        }


        $this->assign('list', $list);

        return $this->fetch('applicationthird_list');
    }

    public function order_confirm(){
        $type = input("type");
        $id = input("id");
        if(empty($type)){
            $this->error('参数错误');
        }
        if(empty($id)){
            $this->error('参数错误');
        }
        switch ($type){
            //酒店订单
            case 1:
                $order = Db::name("hotel_application_order")->where(["id"=>$id,"status"=>2])->find();
                if(empty($order)){
                    $this->error('订单不存在');
                }
                $data = array(
                    "HId"=>$order["h_id"],
                    "RoomId"=>$order["room_id"],
                    "ProductId"=>$order["product_id"],
                    "IsGuarantee"=>$order["is_guarantee"],
                    "InDate"=>$order["in_date"],
                    "OutDate"=>$order["out_date"],
                    "LatestTime"=>$order["latest_time"],
                    "OrderAmount"=>$order["order_amount"],
                    "RoomsCount"=>$order["rooms_count"],
                    "Passengers"=>$order["passengers"],
                    "ContactName"=>$order["contact_name"],
                    "ContactMobile"=>$order["contact_mobile"],
                );
                $format_data = api_format_data($this->api_key(),$this->api_secret(),$data);
                $heades=[
                    'Content-Type:application/json; charset=utf-8',
                ];
                $res=mycurl($this->api_url()."/Hotel/CreateOrder",$format_data,1,$heades);
                $result = json_decode($res,true);

                Db::startTrans();
                try{
                    if(!$result["IsSuccess"]){
                        //订单提交日志
                        ThirdApplicationResultLog::create([
                            "type" => 1,
                            "app_id" => $order["id"],
                            "result_msg" => $result["Message"],
                            "result_status" => 2,
                            "create_time"=>time(),
                            "update_time"=>time()
                        ]);

                        Db::commit();

                    }else{
                        //订单提交日志
                        ThirdApplicationResultLog::create([
                            "type" => 1,
                            "app_id" => $order["id"],
                            "result_msg" => $result["Message"],
                            "result_status" => 1,
                            "create_time"=>time(),
                            "update_time"=>time()
                        ]);
                        //订单状态修改
                        Db::name("hotel_application_order")->save(["order_no"=>$result["Data"]["OrderNo"],"status"=>3,"update_time"=>time()]);
                        Db::commit();

                    }
                }catch(\Exception $e){
                    Db::rollback();
                    $this->error('提交失败'.$e->getMessage());
                }
                $this->success($result["Message"]);
                //火车票订单
            case 2:
                $order = Db::name("train_application_order")->where(["id"=>$id,"status"=>2])->find();
                if(empty($order)){
                    echo json_encode(ajaxreturn(1,lang('订单不存在')));exit;
                }
                $order_info = array(
                    "OrderAmount"=>$order["order_amount"],
                    "TicketFare"=>$order["ticket_fare"],
                    "StartCity"=>$order["start_city"],
                    "EndCity"=>$order["end_city"],
                    "StartDate"=>$order["start_date"],
                    "TrainNo"=>$order["train_no"],
                    "StartTime"=>$order["start_time"],
                    "EndTime"=>$order["end_time"],
                    "ContactName"=>$order["contact_name"],
                    "ContactPhone"=>$order["contact_phone"],
                );
                $order_psg_list = array(
                    array(
                        "PsgName"=>$order["psg_name"],
                        "TicketType"=>$order["ticket_type"],
                        "SeatType"=>$order["seat_type"],
                        "CardType"=>$order["card_type"],
                        "CardNo"=>$order["card_no"],
                        "Phone"=>$order["phone"],
                        "InsProductCode"=>$order["ins_product_code"],
                    )
                );
                $data = array(
                    "OrderInfo"=>$order_info,
                    "OrderPsgList"=>$order_psg_list
                );
                $format_data = api_format_data($this->api_key(),$this->api_secret(),$data);

                $heades=[
                    'Content-Type:application/json; charset=utf-8',
                ];
                $res=mycurl($this->api_url()."/Train/CreateOrder",$format_data,1,$heades);
                $result = json_decode($res,true);


                Db::startTrans();
                try{
                    if(!$result["IsSuccess"]){


                        //订单提交日志
                        ThirdApplicationResultLog::create([
                            "type" => 2,
                            "app_id" => $order["id"],
                            "result_msg" => $result["Message"],
                            "result_status" => 2,
                            "create_time"=>time(),
                            "update_time"=>time()
                        ]);
                        Db::commit();

                    }else{

                        ThirdApplicationResultLog::create([
                            "type" => 2,
                            "app_id" => $order["id"],
                            "result_msg" => $result["Message"],
                            "result_status" => 1,
                            "create_time"=>time(),
                            "update_time"=>time()
                        ]);
                        //订单状态修改
                        Db::name("train_application_order")->where(["id"=>$order["id"]])->update(["order_no"=>$result["Data"]["OrderNo"],"status"=>3,"update_time"=>time()]);
                        Db::commit();

                    }
                }catch (\Exception $e){
                    Db::rollback();
                    $this->error("提交失败".$e->getMessage());
                }
                $this->success($result["Message"]);

                //机票订单
            case 3:
                $order = Db::name("flight_application_order")->where(["id"=>$id,"status"=>2])->find();
                if(empty($order)){
                    $this->error("订单不存在");
                }
                $order_base = array(
                    "FlightType"=>$order["flight_type"],
                    "Amount"=>$order["amount"],
                    "ContactName"=>$order["contact_name"],
                    "ContactMobile"=>$order["contact_mobile"],
                    "OrderRemark"=>$order["order_remark"],
                );

                // $air_lines = array(
                //     array(
                //         "FlightNo"=>$order["flight_no"],
                //         "Cabin"=>$order["cabin"],
                //         "SAirportCode"=>$order["s_airport_code"],
                //         "EAirportCode"=>$order["e_airport_code"],
                //         "STerminal"=>$order["s_terminal"],
                //         "ETerminal"=>$order["e_terminal"],
                //         "FromDateTime"=>$order["from_date_time"],
                //         "ArriveDateTime"=>$order["arrive_date_time"],
                //         "PlaneType"=>$order["plane_type"],
                //         "Fare"=>$order["fare"],
                //         "Oil"=>$order["oil"],
                //         "Tax"=>$order["tax"],
                //         "Discount"=>$order["discount"],
                //     )
                // );
                $air_lines = json_decode($order['air_lines'],1);
                $passengers = array(
                  array(
                      "PsgType"=>$order["psg_type"],
                      "PsgName"=>$order["psg_name"],
                      "CardType"=>1,
                      "CardNo"=>$order["card_no"],
                      "Mobile"=>$order["mobile"],
                      "InsProductCodes"=>$order["ins_product_code"],
                      "BirthDay"=>$order["birth_day"],
                  )
                );
                $policy = array(
                    "BookData"=>$order["book_data"],
                );
                $data = array(
                    "OrderBase"=>$order_base,
                    "AirLines"=>$air_lines,
                    "Passengers"=>$passengers,
                    "Policy"=>$policy
                );
                $format_data = api_format_data($this->api_key(),$this->api_secret(),$data);
                $heades=[
                    'Content-Type:application/json; charset=utf-8',
                ];
                $res=mycurl($this->api_url()."/Flight/CreateOrder",$format_data,1,$heades);
                $result = json_decode($res,true);

                Db::startTrans();
                try{
                    if(!$result["IsSuccess"]){
                        //订单提交日志
                        ThirdApplicationResultLog::create([
                            "type" => 3,
                            "app_id" => $order["id"],
                            "result_msg" => $result["Message"],
                            "result_status" => 2,
                            "create_time"=>time(),
                            "update_time"=>time()
                        ]);

                        Db::commit();

                    }else{
                        //订单提交日志
                        ThirdApplicationResultLog::create([
                            "type" => 2,
                            "app_id" => $order["id"],
                            "result_msg" => $result["Message"],
                            "result_status" => 1,
                            "create_time"=>time(),
                            "update_time"=>time()
                        ]);
                        //订单状态修改
                        Db::name("flight_application_order")->where(["id"=>$id])->update(["order_no"=>$result["Data"]["OrderNo"],"status"=>3,"update_time"=>time()]);
                        Db::commit();

                    }
                }catch(\Exception $e){
                    Db::rollback();
                    $this->error('提交失败'.$e->getMessage());
                }
                $this->success($result['Message']);
                //话费订单
            case 4:
                $order = Db::name("mobile_application_order")->where(["id"=>$id,"status"=>2])->find();
                if(empty($order)){
                    $this->error("订单不存在");
                }
                $telRechargeRes = $this->telcz($order['mobile'],$order['price'],$order['sn']); #可以选择的面额5、10、20、30、50、100、300
        
                if($telRechargeRes['error_code'] !='0'){
                    $this->error('提交失败'.$telRechargeRes['message']);
                }

                Db::startTrans();
                try{
                    if($telRechargeRes['error_code'] !='0'){
                        //订单提交日志
                        ThirdApplicationResultLog::create([
                            "type" => 5,
                            "app_id" => $order["id"],
                            "result_msg" => $telRechargeRes["Message"],
                            "result_status" => 2,
                            "create_time"=>time(),
                            "update_time"=>time()
                        ]);

                        Db::commit();
                    }else{
                        //订单提交日志
                        ThirdApplicationResultLog::create([
                            "type" => 1,
                            "app_id" => $order["id"],
                            "result_msg" => $telRechargeRes["message"],
                            "result_status" => 1,
                            "create_time"=>time(),
                            "update_time"=>time()
                        ]);
                        //订单状态修改
                        Db::name("mobile_application_order")->save(["order_no"=>$result["Data"]["OrderNo"],"status"=>3,"update_time"=>time()]);
                        Db::commit();
                    }
                }catch(\Exception $e){
                    Db::rollback();
                    $this->error("提交失败".$e->getMessage());
                }
            case 5:


        }

    }





}
